package com.mine.service;

import com.mine.config.MailUtil;
import com.mine.dao.UserMapper;
import com.mine.pojo.Meal;
import com.mine.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    //注册
    public boolean addUser(User user) {
        return userMapper.addUser(user);
    }

    //通过username查找对象
    public User getUserByName(String name) {
        return userMapper.getUserByName(name);
    }
    //更新用户信息
    @Transactional
    public User updateUser(User user) {
        userMapper.updateUser(user);
        return userMapper.getUserByName(user.getUsername());
    }

    @Transactional
    public User verification(User user) {
        if (user != null) {
            User user1 = userMapper.getUserByName(user.getUsername());
            return user1;
        }
        return null;
    }

    //获取邮件验证码
    @Transactional
    public int verifeCode(User user) throws MessagingException {
        if (user != null) {
            User user1 = userMapper.getUserByName(user.getUsername());
            System.out.println("============hxd=========="+user1);
            int verificationCode = (int) ((Math.random() * 9 + 1) * 100000);
            //email用户填写的电子邮件    emailCode验证码
            MailUtil.sendMail(user1.getEmail(), verificationCode);
            return verificationCode;
        }
        return 0;
    }
    //修改密码
    @Transactional
    public void modifyUserPassword(User user) {
        userMapper.modifyUserPassword(user);
    }
    //查找我的收藏
    @Transactional
    public List<Meal> queryCollectMealByUser(User user) {
        List split = Arrays.asList(user.getCollect().split("\\|"));
        List<Meal> mealList = userMapper.queryCollectMealByUser(split);
        return mealList;
    }

    public List<User> queryAllUser() {
        return userMapper.queryAllUser();
    }
}
